package com.cl.erp.controller;

import com.cl.erp.entity.AuthUser;
import com.cl.erp.util.JwtTokenUtils;
import com.cl.erp.util.R;
import com.cl.erp.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final JwtTokenUtils jwtTokenUtils;
    private final UserDetailsService userDetailsService;
    private final AuthenticationManager authenticationManager;

    @GetMapping("getUser")
    public R<AuthUser> getUser() {
        AuthUser user = SecurityUtils.getUser();
        return R.ok(user);
    }

    @GetMapping("login")
    public R<String> login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken( username, password );

        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        AuthUser authUser = SecurityUtils.getUser();

        String token = jwtTokenUtils.generateToken(authUser);
        return R.ok(token);
    }
}
